//
//  RecommendViewController.m
//  UI_HLJ_Frame
//
//  Created by  毕宏伟 on 15/6/29.
//  Copyright (c) 2015年 毕宏伟. All rights reserved.
//
#import "themeDetailsViewController.h"
#import "MerchantDetailsViewController.h"
#import "RecommendViewController.h"
#import "ShopTableViewCell.h"
#import "themeTableViewCell.h"
#import "HTTPTool.h"
#import "AFNetworking.h"
#import "UIImageView+WebCache.h"
#import "lunbotuModel.h"
#import "weddingThingModel.h"
#import "MyCell.h"
#import "shopViewController.h"
#import "themeViewController.h"
#import "thingViewController.h"

#import "MBProgressHUD.h"
#import "shopModel.h"
#import "shopCell.h"
#import "shopTableViewCell.h"


#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height


#import "thingdetailsViewController.h"
#import "MJRefresh.h"


@interface RecommendViewController ()<UITableViewDataSource,clicktheme,UITableViewDelegate,click,UICollectionViewDelegate,UICollectionViewDataSource>
@property(nonatomic,retain)UITableView * Tableview;
@property(nonatomic,retain)UIScrollView *  Scrollview;
@property(nonatomic,retain)UIView *headerView;
@property(nonatomic,retain)NSMutableArray *lunbotuModelArr;
@property(nonatomic,retain)NSMutableArray *lunbotupicArr;
@property(nonatomic,retain)UICollectionView *collectionView;
@property (retain,nonatomic) NSMutableArray  *heightArr;
@property (retain,nonatomic) NSMutableArray  *thingArr;
@property(assign ,nonatomic) CGFloat imagehight;

@property(nonatomic,retain)MBProgressHUD *hud;

@property(nonatomic,retain)UIView *titleView;
@end

@implementation RecommendViewController
-(void)dealloc{
    
    [_titleView release];
    [_thingArr release];
    [_heightArr release];
    [_collectionView release];
    [_lunbotuModelArr release];
    [_lunbotupicArr release];
    [_headerView release];
    [_Scrollview release];
   [_Tableview release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
  
   
    // Do any additional setup after loading the view.

  // 导航栏不透明
    self.navigationController.navigationBar.translucent=NO;
    
    self.title= @"主题";
  
 
    
    [self createData];
    
    [self createView];
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self.view addSubview:self.hud];
    self.hud.labelText = @"loading...";
}

-(void)createView{
    // 轮播图
    
    self.headerView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 150)];
    self.headerView.backgroundColor = [UIColor colorWithRed:0.609 green:1.000 blue:0.900 alpha:1.000];
    [self.view addSubview:self.headerView];
    [self.headerView release];
 
    self.Scrollview = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 150)];
    self.Scrollview.backgroundColor=[UIColor whiteColor];
    [self.headerView addSubview:self.Scrollview];
    [_Scrollview release];
    
    
    self.Scrollview.pagingEnabled =YES;
    self.Scrollview.showsHorizontalScrollIndicator = NO;
    //设置初始位置
        self.Scrollview.contentOffset = CGPointMake(WIDTH, 0);

    [self.Scrollview alwaysBounceHorizontal];
    [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(timer) userInfo:nil repeats:YES];

    
    
    
    self.Tableview = [[UITableView alloc ]initWithFrame:CGRectMake(0, 00, self.view.frame.size.width, self.view.frame.size.height-49-64) style:UITableViewStylePlain];
    self.Tableview.delegate=self;
    self.Tableview.dataSource=self;
    [self.Tableview release];
 //不显示cell间分割线
    self.Tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    //每一个item的大小
    flowLayout.itemSize = CGSizeMake((self.view.frame.size.width/2-50), 85);
    //设置最小的行间距
//    flowLayout.minimumLineSpacing = 20;
//    //设置最小的列间距
//    flowLayout.minimumInteritemSpacing =40;
    //滑动的方向,默认是垂直滑动
    //    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    // 靠近屏幕边缘的距离
    //    flowLayout.sectionInset = UIEdgeInsetsMake(00, 0, 400, 0);
    
    //如果要给collectionView一个头或者尾添加一个视图,不能像tableview一样,只能写一个自定义的视图
    // 垂直滑动设定高度
    // 水平滑动设置宽度
    //    flowLayout.headerReferenceSize = CGSizeMake(0, 300);
    self.heightArr=[[NSMutableArray array]init];
    

    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) collectionViewLayout:flowLayout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor=[UIColor whiteColor];

    [self.collectionView addFooterWithTarget:self action:@selector(footerRereshing)];
//    [self.view addSubview:self.collectionView];

    
    self.Tableview.tableHeaderView = self.headerView;
//    self.Tableview.tableFooterView.frame=CGRectMake(0, self.view.frame.size.height-49-64, 375, 20);
    self.Tableview.tableFooterView = self.collectionView;
  [self.collectionView registerClass:[MyCell class] forCellWithReuseIdentifier:@"MyCell"];
    [self.collectionView release];

 [self.view addSubview:self.Tableview];
}

//数据解析
- (void)createData
{

    
    self.lunbotuModelArr=[NSMutableArray array];
    self.thingArr  = [NSMutableArray array];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:@"http://hunliji.com/v2/api/app/banners.json?site=6" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
       NSMutableArray *arr = responseObject;
        
        for (NSDictionary *tempdic in arr) {
            lunbotuModel  *tu= [[lunbotuModel alloc]init];
            [tu setValuesForKeysWithDictionary:tempdic];
         
            [self.lunbotuModelArr addObject:tu];
           
            [self createscrollview];
        
            [tu release];
        }

        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        
    }];
   [manager GET:@"http://www.hunliji.com/v1/api/app/products.json?per_page=20&page=1" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
       NSMutableDictionary *dic = responseObject;
       NSMutableArray *arr = dic[@"products"];
       for (NSDictionary *tempdic in arr) {
           weddingThingModel *thing= [[weddingThingModel alloc]init];
           [thing setValuesForKeysWithDictionary:tempdic];
           [self.thingArr addObject:thing];
           [thing release];
       }
       [self.collectionView reloadData];
       [self.Tableview reloadData];
       [self.hud hide:YES afterDelay:1];
       
   } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
       
       
       
   }];
}


- (void)footerRereshing
{ static NSInteger a=2;
    NSString *url = [NSString stringWithFormat:@"http://www.hunliji.com/v1/api/app/products.json?per_page=20&page=%ld",a];
    AFHTTPRequestOperationManager *homecellmanager = [AFHTTPRequestOperationManager manager];
    [homecellmanager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSMutableDictionary *dic = responseObject;
        NSMutableArray *arr = dic[@"products"];
        for (NSDictionary *tempdic in arr) {
            weddingThingModel *thing= [[weddingThingModel alloc]init];
            [thing setValuesForKeysWithDictionary:tempdic];
            [self.thingArr addObject:thing];
            [thing release];
        }
        [self.collectionView reloadData];
        [self.collectionView footerEndRefreshing];
        a++;
    }
     
    failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}



- (void)timer {
    
    CGPoint point = CGPointMake(self.Scrollview.contentOffset.x + WIDTH, 0);
    [self.Scrollview setContentOffset:point animated:YES];
    // 图片自动滚动后判断偏移量,如果是最后一张图就直接设置偏移量到第二张图.实现无限滚动
    if (self.Scrollview.contentOffset.x == (self.lunbotupicArr.count-1)* WIDTH) {
        self.Scrollview.contentOffset = CGPointMake(WIDTH, 0);
    }
}
//创建scrollview
- (void)createscrollview {
    self.lunbotupicArr = [[NSMutableArray array]init];

    //self.page.numberOfPages = self.lunboPicArr.count-2;
    
    self.Scrollview.contentOffset = CGPointMake(WIDTH, 0);
    for (NSInteger i = 0; i < self.lunbotuModelArr.count; i++) {
        lunbotuModel  *tu = [[lunbotuModel alloc]init];
        tu = self.lunbotuModelArr[i];
        [self.lunbotupicArr addObject:tu.image_path];}
        NSString *lastStr = [self.lunbotupicArr lastObject];
        [self.lunbotupicArr insertObject:lastStr atIndex:0];
        NSString *firstStr = self.lunbotupicArr[1];
        [self.lunbotupicArr insertObject:firstStr atIndex:self.lunbotupicArr.count];
    self.Scrollview.contentSize =CGSizeMake(self.lunbotupicArr.count*WIDTH, 0);
    for (NSInteger i=0; i<self.lunbotupicArr.count; i++) {

        UIImageView *imageView = [[UIImageView alloc] init];
        [imageView sd_setImageWithURL:[NSURL URLWithString:self.lunbotupicArr[i] ]];

        imageView.frame = CGRectMake(WIDTH * i, 0, WIDTH, 150);
        [self.Scrollview addSubview:imageView];
        [imageView release];
    }
}



-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger section = indexPath.section;
    if (section==0)
    { static NSString * reuse= @"reuse";
    ShopTableViewCell *cell= [tableView dequeueReusableCellWithIdentifier:reuse];
        cell.delegatey=self;
        if (!cell) {
        cell = [[ShopTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }

        return cell;
    }else  if(section==1){
                static NSString * reuse= @"themereuse";
                themeTableViewCell *cell= [tableView dequeueReusableCellWithIdentifier:reuse];
        cell.delegatett=self;
                if (!cell) {
                    cell = [[themeTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse];
                    cell.selectionStyle = UITableViewCellSelectionStyleNone;
                }
                return cell;
    }else{
        static NSString * reuse= @"reuse1";
        UITableViewCell *cell= [tableView dequeueReusableCellWithIdentifier:reuse];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        return cell;
    }
}

//
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (section==0) {
        return @"服务商家推荐";
    }else if(section==1)
    { return @"主题婚品";}
    else return @"商品推荐";
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
NSInteger section = indexPath.section;
    if (section==0) {
        return 100;
    }else if(section==1)
    {  return 150;}
    else return 0;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//通过比例 算每个cell 的高 放数组里
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
     weddingThingModel  *thing = self.thingArr[indexPath.row];
      CGFloat a=[thing.height floatValue];
      CGFloat b =[thing.width floatValue];
    CGFloat height = (a/b*self.view.frame.size.width/2)+30;
    [self.heightArr addObject:[NSString stringWithFormat:@"%f",height]];
    

    return  CGSizeMake((self.view.frame.size.width/2)-20, height);
}
//在自定义cell 里算每个的位置
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    MyCell *myCell=[collectionView dequeueReusableCellWithReuseIdentifier:
                    @"MyCell" forIndexPath:indexPath];
    
  
    //  cell 的动画
    myCell.layer.transform = CATransform3DMakeScale(0.3, 0.3, 0.1);
    [UIView animateWithDuration:0.5 animations:^{
        
        myCell.layer.transform = CATransform3DMakeScale(1, 1, 0.1);
    }];
    
    NSInteger remainder=indexPath.row%2;
    NSInteger currentRow=indexPath.row/2;

    // 根据高度设置 初始位置
    CGFloat   currentHeight=[self.heightArr[indexPath.row] floatValue];
    myCell.hightimage = currentHeight;
    CGFloat positonX=(self.view.frame.size.width/2-10)*remainder+10*(remainder+1);
    CGFloat positionY=(currentRow+1)*10;
    for (NSInteger i=0; i<currentRow; i++) {
        NSInteger position=remainder+i*2;
        positionY+=[self.heightArr[position] floatValue];
    }
    myCell.frame = CGRectMake(positonX, positionY,(self.view.frame.size.width/2-20),currentHeight) ;

    //给cell赋值
      weddingThingModel  *thing = self.thingArr[indexPath.row];
    [myCell.myImageView sd_setImageWithURL:[NSURL URLWithString:thing.photo_path] placeholderImage:[UIImage imageNamed:@"占位图"]];
//    [myCell.myImageView sd_setImageWithURL:[NSURL URLWithString:thing.photo_path ]];
  myCell.myLabel.text= [NSString stringWithFormat:@"￥%@",thing.price];

    return  myCell;
} 
//商家的点击方法
-(void)click:(UIButton *)button model:(shopModel *)model{

    MerchantDetailsViewController *MDVC=[[MerchantDetailsViewController alloc]init];
    [self.navigationController pushViewController:MDVC animated:YES];
    CGFloat a = [model.bid floatValue];
    MDVC.merchantIdStr= [NSNumber numberWithFloat:a];
    MDVC.coverStr = model.cover_path;
    MDVC.logoStr = model.logo_path;
    MDVC.nameStr = model.name;
    MDVC.addressStr = model.address;

}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.thingArr.count;
}


//section 的view 设置
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section ==0) {
        
        self.titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)];
        self.titleView.backgroundColor = [UIColor colorWithRed:1.000 green:0.503 blue:0.713 alpha:1.000];
        UILabel *leftLabel =[[UILabel alloc]initWithFrame:CGRectMake(10,1,120, 30)];
        leftLabel.text = @"服务商家展示";
        
        [self.titleView addSubview:leftLabel];
        UIButton *moreButton = [UIButton buttonWithType:UIButtonTypeCustom];

        [moreButton setTitle:@"详情 >" forState:UIControlStateNormal];

        [moreButton setTitleColor:[UIColor whiteColor]forState:UIControlStateNormal];
        [moreButton addTarget:self action:@selector(shopclick:) forControlEvents:UIControlEventTouchUpInside];
        moreButton.frame = CGRectMake(WIDTH * 1.6 / 2, 10, 60, 10);
        [self.titleView addSubview:moreButton];
        
        [_titleView release];
        return self.titleView;
        
    }
    else if (section==1)
    {
        self.titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)];
        self.titleView.backgroundColor = [UIColor colorWithRed:1.000 green:0.503 blue:0.713 alpha:1.000];
        UILabel *leftLabel =[[UILabel alloc]initWithFrame:CGRectMake(10,1,120, 30)];
        leftLabel.text = @"主题婚品展示";
        
        [self.titleView addSubview:leftLabel];
        UIButton *moreButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [moreButton setTitle:@"详情 >" forState:UIControlStateNormal];
        [moreButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        moreButton.frame = CGRectMake(WIDTH * 1.6 / 2, 10, 60, 10);
        [moreButton addTarget:self action:@selector(themeclick:) forControlEvents:UIControlEventTouchUpInside];
        [self.titleView addSubview:moreButton];
        
        [_titleView release];
        return self.titleView;
    }
    
    else if (section==2)
    {
        self.titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)];
        self.titleView.backgroundColor = [UIColor colorWithRed:1.000 green:0.503 blue:0.713 alpha:1.000];
        UILabel *leftLabel =[[UILabel alloc]initWithFrame:CGRectMake(10,1,120, 30)];
        leftLabel.text = @"商品推荐";
        
        [self.titleView addSubview:leftLabel];
        UIButton *moreButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [moreButton setTitle:@"更多 >" forState:UIControlStateNormal];
        [moreButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        moreButton.frame = CGRectMake(WIDTH * 1.6 / 2, 10, 60, 10);
        [moreButton addTarget:self action:@selector(thingclick:) forControlEvents:UIControlEventTouchUpInside];
        [self.titleView addSubview:moreButton];
        [_titleView release];
        return self.titleView;
        
    }
    
    else
    {
        return nil;
    }
}
//物品的点击方法
-(void)thingclick:(UIButton *)button{
    thingViewController *thingVC = [[thingViewController alloc]init];
    [self.navigationController pushViewController:thingVC animated:YES];
}


-(void)shopclick:(UIButton *)button{
    shopViewController *shopVC = [[shopViewController alloc]init];
    // 网络请求
    shopVC.shopStr = @"http://hunliji.com/v1/api/app/merchants.json?page=1&per_page=20&property=2";
    shopVC.shopStr1 = @"http://hunliji.com/v1/api/app/merchants.json?page=1&per_page=20&property=6";
    shopVC.shopStr2 = @"http://hunliji.com/v1/api/app/merchants.json?page=1&per_page=20&property=7";
    shopVC.shopStr3 = @"http://hunliji.com/v1/api/app/merchants.json?page=1&per_page=20&property=8";
    shopVC.shopStr4 = @"http://hunliji.com/v1/api/app/merchants.json?page=1&per_page=20&property=9";
    shopVC.shopStr5 = @"http://hunliji.com/v1/api/app/merchants.json?page=1&per_page=20&property=11";
    
    [self.navigationController pushViewController:shopVC animated:YES];
    

}
//主题点击方法
-(void)themeclick:(UIButton *)button{
    themeViewController *themeVC=[[themeViewController alloc]init];
    [self.navigationController pushViewController:themeVC animated:YES];
    
}
//  商品点击方法 通过传id 跳转
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    thingdetailsViewController *thingdetailsVC = [[thingdetailsViewController alloc]init];
    [self.navigationController pushViewController:thingdetailsVC animated:YES];
weddingThingModel *thing= [[weddingThingModel alloc]init];
  thing =  self.thingArr[indexPath.row];
    thingdetailsVC.bid = thing.bid;
}
//主题点击方法
-(void)clicktt:(UIButton *)button model:(themeModel *)model{

    themeDetailsViewController  *themeVC=[[themeDetailsViewController alloc]init];
    [self.navigationController pushViewController:themeVC animated:YES];
    themeVC.bid = model.bid;
    themeVC.bkgimage= model.bkg_path;
    themeVC.Desc =model.desc;
    themeVC.title = model.title;

}
-(void)viewWillAppear:(BOOL)animated{





}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
